package cn.toma.service.impl.sys;

import cn.toma.core.AbstractService;
import cn.toma.dao.sys.UserRoleMapper;
import cn.toma.model.sys.UserRole;
import cn.toma.service.sys.UserRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service("userRoleService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class UserRoleServiceImpl extends AbstractService<UserRole> implements UserRoleService
{

	@Resource
	private UserRoleMapper userRoleMapper;

	@Override
	@Transactional
	public void deleteUserRolesByRoleId(String[] roleIds)
	{
		Arrays.stream(roleIds).forEach(id -> userRoleMapper.deleteByRoleId(Long.valueOf(id)));
	}

	@Override
	@Transactional
	public void deleteUserRolesByUserId(String[] userIds)
	{
		Arrays.stream(userIds).forEach(id -> userRoleMapper.deleteByUserId(Long.valueOf(id)));
	}

	@Override
	public List<String> findUserIdsByRoleId(String[] roleIds)
	{
		Weekend<UserRole> weekend = new Weekend<>(UserRole.class);
		WeekendCriteria<UserRole, Object> weekendCriteria = weekend.weekendCriteria();
		weekendCriteria.andIn(UserRole::getRoleId, Arrays.asList(roleIds));
		List<UserRole> userRoles = this.userRoleMapper.selectByCondition(weekend);
		return userRoles.stream().map(userRole -> String.valueOf(userRole.getUserId())).collect(Collectors.toList());
	}

}
